package thread.sysChronize;

/**
 * 线程同步
 * @Author Janson
 * @Date 2022/2/27 15:45
 * @Version 1.0
 */
public class TestThreadSysChronized {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket,"小黑").start();
        new Thread(buyTicket,"小白").start();
        new Thread(buyTicket,"小黄牛").start();
        //String name = buyTicket.getClass().getName();
        //System.out.println(name);
        //String simpleName = buyTicket.getClass().getSimpleName();
        //System.out.println(simpleName);
    }
}
class BuyTicket implements Runnable{
    private int ticket = 10;
    //线程停止标志位
    private boolean flag  = true;
    @Override
    public void run() {
        while (flag){
            buy();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //采用线程锁，synchronized ，既可以锁方法，又可以 锁代码块
    public  synchronized void buy(){
        //判断是否有票
        if (ticket<=0){
            flag = false;
            return;
        }
        System.out.println(Thread.currentThread().getName() + "买到了第 " + ticket-- + " 票");

    }
}

